//
//  WHAddShopController.m
//  SquirrelCourier
//
//  Created by 邓伟浩 on 2019/1/4.
//  Copyright © 2019 邓伟浩. All rights reserved.
//

#import "WHAddShopController.h"
#import "WHEditMoneyCell.h"
#import "WHSelectAddressCell.h"
#import "WHShopNameController.h"
#import "WHTextInfoController.h"

@interface WHAddShopController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *dataTableView;
@property (nonatomic, assign) double money;

@end

@implementation WHAddShopController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if (self.shopType == ShopTypeEdit) {
        self.navigationItem.title = @"修改存管费";
    } else if (self.shopType == ShopTypeReply) {
        self.navigationItem.title = @"重新申请";
    } else {
        self.navigationItem.title = @"新增合作门店";
    }
    _money = self.nameModel.saveMoney.doubleValue;
    
    [self setUpTableView];
}

- (WHStationNameModel *)nameModel {
    if (!_nameModel) {
        _nameModel = [[WHStationNameModel alloc] init];
        _nameModel.saveMoney = @"0.6";
        
    }
    return _nameModel;
}

- (void)setUpTableView {
    UITableView *dataTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    dataTableView.delegate = self;
    dataTableView.dataSource = self;
    [self.view addSubview:dataTableView];
    
    [dataTableView registerClass:[WHEditMoneyCell class] forCellReuseIdentifier:NSStringFromClass([WHEditMoneyCell class])];
    [dataTableView registerClass:[WHSelectAddressCell class] forCellReuseIdentifier:NSStringFromClass([WHSelectAddressCell class])];
    
    dataTableView.tableFooterView = [self tableFooterView];
    dataTableView.backgroundColor = CViewBgMainColor;
    dataTableView.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);
    dataTableView.separatorColor = CLineColor;
    
    [dataTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(self.view);
        make.top.equalTo(@kTopHeight);
    }];
    _dataTableView = dataTableView;
}

- (UIView *)tableFooterView {
    UIView *tableFooterView = [[UIView alloc] init];
    tableFooterView.frame = CGRectMake(0, 0, KScreenWidth, kRealwidth(125));
    
    UIButton *startCoopBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    ViewRadius(startCoopBtn, kRealwidth(45)/2);
    [tableFooterView addSubview:startCoopBtn];
    [startCoopBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(KScreenWidth-2*kRealwidth(32));
        make.centerX.mas_equalTo(tableFooterView.mas_centerX);
        make.height.mas_equalTo(kRealwidth(45));
        make.top.mas_equalTo(tableFooterView.mas_top).offset(kRealwidth(20));
    }];
    NSString *startCoopTitle = @"发起合作";
    NSAttributedString *attributeStr = [[NSAttributedString alloc] initWithString:startCoopTitle attributes:@{NSFontAttributeName:SYSTEMFONT(kRealwidth(17)), NSForegroundColorAttributeName:KWhiteColor}];
    [startCoopBtn setAttributedTitle:attributeStr forState:UIControlStateNormal];
    startCoopBtn.backgroundColor = CMDarkOrangeColor;
    
    UIButton *acceptRuleButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [tableFooterView addSubview:acceptRuleButton];
    [acceptRuleButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(KScreenWidth-2*kRealwidth(32));
        make.centerX.mas_equalTo(tableFooterView.mas_centerX);
        make.height.mas_equalTo(kRealwidth(14));
        make.top.mas_equalTo(startCoopBtn.mas_bottom).offset(kRealwidth(25));
    }];
    NSString *acceptText = @"发起合作后，即同意";
    NSMutableAttributedString *acceptAttrStr = [[NSMutableAttributedString alloc] initWithString:acceptText attributes:@{NSForegroundColorAttributeName:CFontContentLightGrayColor, NSFontAttributeName:SYSTEMFONT(kRealwidth(14))}];
    NSString *serviceText = @"《松鼠侠协议》";
    NSMutableAttributedString *serviceAttrStr = [[NSMutableAttributedString alloc] initWithString:serviceText attributes:@{NSForegroundColorAttributeName:CMDarkOrangeColor, NSFontAttributeName:SYSTEMFONT(kRealwidth(14))}];
    [acceptAttrStr appendAttributedString:serviceAttrStr];
    [acceptRuleButton setAttributedTitle:acceptAttrStr forState:UIControlStateNormal];
    
    [startCoopBtn addTarget:self action:@selector(startCoop:) forControlEvents:UIControlEventTouchUpInside];
    [acceptRuleButton addTarget:self action:@selector(acceptRule:) forControlEvents:UIControlEventTouchUpInside];
    
    return tableFooterView;
}

#pragma mark - —————— UITableViewDelegate & UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        WHSelectAddressCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([WHSelectAddressCell class]) forIndexPath:indexPath];
        if (self.shopType == ShopTypeAdd) {
            cell.rightTipsImageView.hidden = NO;
        } else {
            cell.rightTipsImageView.hidden = YES;
        }
        cell.addressName = self.nameModel.stationName;
        
        return cell;
    } else {
        WHEditMoneyCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([WHEditMoneyCell class]) forIndexPath:indexPath];
        cell.money = _money;
        kWeakSelf(self);
        cell.moneyChange = ^(double money) {
            weakself.money = money;
            weakself.nameModel.saveMoney = NSStringFormat(@"%.1f", money);
        };
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return kRealwidth(55);
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.shopType == ShopTypeAdd) {
        if (indexPath.row == 0) {
            WHShopNameController *shopName = [[WHShopNameController alloc] init];
            [self.navigationController pushViewController:shopName animated:YES];
            kWeakSelf(self);
            shopName.selectShopName = ^(WHStationNameModel * _Nonnull stationModel) {
                weakself.nameModel.stationName = stationModel.stationName;
                weakself.nameModel.stationId = stationModel.stationId;
                [weakself.dataTableView reloadData];
            };
        }
    }
}

#pragma mark - —————— 事件 ——————
- (void)startCoop:(UIButton *)button {
    DLog(@"门店名称: %@, 存管费: %@", self.nameModel.stationName, self.nameModel.saveMoney);
    if (!ValidStr(self.nameModel.stationName)) {
        [WHView showAlertwithTitle:nil message:@"请选择门店名称"];
        return;
    }
    
    if (self.shopType == ShopTypeAdd) {
        [self joinStation];
    } else {
        [self updateSaveMoney];
    }
}

- (void)acceptRule:(UIButton *)button {
    DLog(@"acceptRule");
    WHTextInfoController *textInfo = [[WHTextInfoController alloc] init];
    textInfo.urlstr = URL_agreement;
    [self.navigationController pushViewController:textInfo animated:YES];
}

#pragma mark - —————— 接口 ——————
- (void)joinStation {
    NSString *postURL = NSStringFormat(@"%@%@", URL_main, URL_insertJoinstation);
    
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                          @(userManager.detailUserInfo.userId), @"userId",
                          self.nameModel.saveMoney, @"saveMoney",
                          self.nameModel.stationId, @"stationId",
                          self.nameModel.stationName, @"stationName",
                          nil];
    
    [WHNetworkManager requestWithURL:postURL parameters:dict isUpData:YES Success:^(id responseObject) {
        DLog(@"%@", responseObject);
        if (ValidDict(responseObject)) {
            NSNumber *code = responseObject[@"errcode"];
            NSString *errorMsg = responseObject[@"errmsg"];
            if (code.intValue == 0) {
                [WHView showAlertwithTitle:nil message:@"发起合作成功"];
                [self.navigationController popToRootViewControllerAnimated:YES];
            } else {
                [WHView showHudMsg:errorMsg];
            }
        }
    } failure:^(NSError *error) {
        
    }];
}

- (void)updateSaveMoney {
    NSString *postURL = NSStringFormat(@"%@%@", URL_main, URL_updateSaveMoney);
    
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                          @(userManager.detailUserInfo.userId), @"userId",
                          self.nameModel.saveMoney, @"modifyMoney",
                          self.nameModel.stationId, @"stationId",
                          nil];
    
    [WHNetworkManager requestWithURL:postURL parameters:dict isUpData:YES Success:^(id responseObject) {
        DLog(@"%@", responseObject);
        if (ValidDict(responseObject)) {
            NSNumber *code = responseObject[@"errcode"];
            NSString *errorMsg = responseObject[@"errmsg"];
            if (code.intValue == 0) {
                if (self.shopType == ShopTypeEdit) {
                    [WHView showAlertwithTitle:nil message:@"修改存管费成功,请等待审核"];
                } else if (self.shopType == ShopTypeReply) {
                    [WHView showAlertwithTitle:nil message:@"重新发起合作成功,请等待审核"];
                }
                
                [self.navigationController popViewControllerAnimated:YES];
            } else {
                [WHView showHudMsg:errorMsg];
            }
        }
    } failure:^(NSError *error) {
        
    }];
    
    
}

@end
